import { createStore } from 'vuex'
import { Toast } from 'vant'
export type CartItemType = {
  id: number
  count: number
  price: number
  img: string
  goodsName: string
}

interface StoreState {
  cartList: CartItemType[]
}

export default createStore<StoreState>({
  state: {
    cartList: [],
  },
  mutations: {
    SET_CART_LIST(state, item) {
      // 1. 判断是否重复
      const goods = state.cartList.find((v) => v.id === item.id)
      if (goods) {
        goods.count++
      } else {
        Toast.success('添加成功')
        state.cartList.push(item)
      }
    },
    SET_ADD_ITEM(state, item) {
      item.count++
    },
    SET_REDUCE_ITEM(state, item) {
      if (item.count <= 1) {
        if (window.confirm('确定删除吗？')) {
          const removeIndex = state.cartList.findIndex((v) => v.id === v.id)
          state.cartList.splice(removeIndex, 1)
          Toast.success('删除成功')
        }
        return
      }
      item.count--
    },
  },
  getters: {
    totalPrice(state) {
      return state.cartList.reduce((num, item) => {
        return num + item.count * item.price
      }, 0)
    },
  },
  actions: {},
  modules: {},
})
